import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Transactions } from '../api/transaction/transactions.js';
import { Session } from 'meteor/session'
import Snackbar from 'material-ui/Snackbar';

import {List, ListItem} from 'material-ui/List';
import InfiniteScroll from 'react-infinite-scroller';

import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Avatar from 'material-ui/Avatar';
import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem'; 
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import NavigationLeft from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import AppBar from 'material-ui/AppBar';

import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';

let faker = require('faker/locale/zh_CN');

const styles = {
  toolbar:{
    position: 'fixed',
    top: 0,
    width: '100%',
  },
  dlg:{
    width: '100%',
    maxWidth: 'none',    
  }
}



var myallprojects = [];
var trademenus = [];

export class Tab1List extends Component {
  constructor(props) {
    super(props);
    this.state = {
        page:0,
        picPos:0,
        hasMore:true,
        items:[],
        ch:0,
        dlg_open_view:false,
        dlg_open_action1:false,
        dlg_open_action2:false,
        snack_open:false,
        snack_msg:'',
    };
    this.btns_action1 = [
      <FlatButton
        label="确定"
        primary={true}
        onTouchTap={e => {
          let me=this;
          Meteor.call('trans.create',
              this.props.cuid,this.props.tuid,this.state.dlgtitle,{
              projectname:this.state.pay_projectname,
              t_desc:this.state.pay_desc
            },
            function(err, result){
              if(err){
                  console.log(err);
                  me.setState({snack_open:true,snack_msg:'交易发送失败：'+err});
              } else {
                me.setState({snack_open:true,snack_msg:'交易已成功发送'});
              }
          });
          this.setState({dlg_open_action1:false});
        }}
      />,
      <FlatButton
        label="取消"
        onTouchTap={e => this.setState({dlg_open_action1:false})}
      />,
    ];
    this.btns_action2 = [
      <FlatButton
        label="确定"
        primary={true}
        onTouchTap={e => {
          let me=this;
          Meteor.call('trans.create',
            this.props.cuid,
            this.props.tuid,
            '申请项目',{
              userId:this.state.u_userId,
              title:this.state.u_title,
              desc:this.state.u_desc,
              projectname:this.state.u_title,
              t_desc:this.state.t_desc,
            },
            function(err, result){
              if(err){
                  console.log(err);
                  me.setState({snack_open:true,snack_msg:'交易发送失败：'+err});
              } else {
                me.setState({snack_open:true,snack_msg:'交易已成功发送'});
              }
          });
          this.setState({dlg_open_action2:false});
        }}
      />,
      <FlatButton
        label="取消"
        onTouchTap={e => this.setState({dlg_open_action2:false})}
      />,
    ];
   
  this.Logged = (props) => (
  <IconMenu
    {...props}
    iconButtonElement={
      <IconButton><MoreVertIcon /></IconButton>
    }
    targetOrigin={{horizontal: 'right', vertical: 'top'}}
    anchorOrigin={{horizontal: 'right', vertical: 'top'}}
  >
  <MenuItem primaryText="申请项目" 
        onTouchTap={e => this.setState({dlg_open_action2:true,
        u_avatar:"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
      })}
      />

      <MenuItem primaryText="申请实施" 
        onTouchTap={e => this.setState({dlg_open_action1:true,dlgtitle:"申请实施"})}
      />
      
      <MenuItem primaryText="申请拨款" 
      onTouchTap={e => this.setState({dlg_open_action1:true,dlgtitle:"申请拨款"})}
      />
      <MenuItem primaryText="申请报账" 
      onTouchTap={e => this.setState({dlg_open_action1:true,dlgtitle:"申请报账"})}
      />
    
  </IconMenu>
);

    
this.Logged.muiName = 'IconMenu';  
}
componentDidMount(x,y,z){
  this.setState({cw:window.innerWidth,ch:window.innerHeight});
}  
renderAppBar(){
  if(this.props.handleClose){
    return (
      <AppBar title="历史交易" 
        style={styles.toolbar}
        iconElementRight={<this.Logged />}
        iconElementLeft={
            <IconButton 
            onTouchTap={this.props.handleClose}
            iconStyle={{width:48,height:48}}
            style={{padding: 0,}}
            ><NavigationLeft /></IconButton>
          }         
      />      
    );
  }else return '';
}
render() {
    let items = this.props.items||[];
    let cuid = this.props.cuid;
    let result = []; 
    //items.reverse();
    items.map((item) => {
      let bFrom = (item.userFrom===cuid);
      let avatar = item.avatarFrom;
      let title = item.tags;
      let tid = item.confirmId||item.transactionId;
      let desc = item.desc+'----'+item.title;
      if(bFrom)
        result.push(
          <ListItem
            key = {item.transactionId}
            style={{textAlign:'right'}}
            onTouchTap={e => this.setState({dlg_open_view:true,view_item:item})}
            rightAvatar={<Avatar src={avatar} />}
            primaryText={title }
            secondaryText={
              <p>
                {desc}
              </p>
            }
            secondaryTextLines={2}
          />        
        );
      else
          result.push(
          <ListItem
            key = {item.transactionId}
            onTouchTap={e => this.setState({dlg_open_view:true,view_item:item})}
            leftAvatar={<Avatar src={avatar} />}
            primaryText={title}
            secondaryText={
              <p>
                {desc}
              </p>
            }
            secondaryTextLines={2}
          />        
        );    
    });

    //判断是否显示‘确认交易’按钮
    let  btns_view = [];
    let vitem = this.state.view_item;
    if(vitem){
      //发送给我的,并且还未确认,确认交易本身不需要再确认
      if(vitem.userTo==this.props.cuid && !vitem.confirmAt && !vitem.confirmId)
        btns_view.push(
      <FlatButton
        label="确认该笔交易"
        onTouchTap={e => {
          let me=this;
          Meteor.call('trans.confirm',this.props.cuid,vitem.transactionId,this.state.u_paynumber,
            function(err, result){
              if(err){
                  console.log(err);
                  me.setState({snack_open:true,snack_msg:'确认交易失败：'+err});
              } else {
                me.setState({snack_open:true,snack_msg:'交易已成功确认'});
              }
          });          
          this.setState({dlg_open_view:false});
        }}
      />          
        );
    }else{
      //默认空数据,避免界面出错
      vitem={};
    }
     
    btns_view.push(
      <FlatButton
        label="取消"
        primary={true}
        onTouchTap={e => this.setState({dlg_open_view:false})}
      />
      );
    

    return (
       <div>    
      {this.renderAppBar()}    
      <div style={{height:this.state.ch,overflowY:'auto'}}>
       <List style={{marginTop:'4em',marginBottom:'4em'}}>
         {result}
       </List>
       </div>
       <Dialog
          contentStyle={styles.dlg}
          actions={btns_view}
          title="查看交易"
          modal={false}
          open={this.state.dlg_open_view}
          openSecondary={true}
          autoScrollBodyContent={true}
          onRequestClose={e => this.setState({dlg_open_view:false})}
        >
      <TextField
        floatingLabelText='交易号'
        floatingLabelFixed={true}
        fullWidth={true}
        value={vitem.transactionId}
      />
      <TextField
        floatingLabelText='交易名'
        floatingLabelFixed={true}
        fullWidth={true}
        value={vitem.title}
      />
      <TextField
        floatingLabelText='发起时间'
        floatingLabelFixed={true}
        fullWidth={true}
        value={vitem.createdAt?vitem.createdAt.toLocaleString():''}
      />

      <TextField
        floatingLabelText='交易金额'
        floatingLabelFixed={true}
        fullWidth={true}
        value={vitem.paynumber}
        onChange={e => this.setState({ "u_paynumber": e.target.value })}
        
      />

      <TextField
        floatingLabelText='确认时间'
        floatingLabelFixed={true}
        fullWidth={true}
        value={vitem.confirmAt?vitem.confirmAt.toLocaleString():''}
      />
      <TextField
        floatingLabelText='交易说明'
        floatingLabelFixed={true}
        fullWidth={true}
        multiLine={true}
        value={vitem.desc}
      />
      <TextField
        floatingLabelText='交易数据'
        floatingLabelFixed={true}
        fullWidth={true}
        multiLine={true}
        value={JSON.stringify(vitem.data)}
      />
    </Dialog>

    <Dialog
          contentStyle={styles.dlg}
          actions={this.btns_action1}
          title={this.state.dlgtitle}
          modal={false}
          open={this.state.dlg_open_action1}
          openSecondary={true}
          onRequestClose={e => this.setState({dlg_open_action1:false})}
        >
       <SelectField 
        floatingLabelText='选择项目'
        floatingLabelFixed={true}
        fullWidth={true}
        value={this.state.pay_projectname}
        onChange={(event, index, values) => this.setState({"pay_projectname":values})}
         >
        {myallprojects}
       </SelectField>

      <TextField
        floatingLabelText='申请说明'
        floatingLabelFixed={true}
        fullWidth={true}
        multiLine={true}
        onChange={e => this.setState({ pay_desc: e.target.value })}
      />
    </Dialog>

    <Dialog
          contentStyle={styles.dlg}
          actions={this.btns_action2}
          title="建立项目"
          modal={false}
          open={this.state.dlg_open_action2}
          openSecondary={true}
          onRequestClose={e => this.setState({dlg_open_action2:false})}
        >
       <Avatar src={this.state.u_avatar} />
      <TextField
        floatingLabelText='项目编号'
        floatingLabelFixed={true}
        //value={this.state.u_userId}
        onChange={e => this.setState({ u_userId: e.target.value })}
        fullWidth={true}
      />

      <TextField
        floatingLabelText='项目名称'
        floatingLabelFixed={true}
        onChange={e => this.setState({ u_title: e.target.value })}
        fullWidth={true}
      />

      <TextField
        floatingLabelText='项目说明'
        floatingLabelFixed={true}
        fullWidth={true}
        multiLine={true}
        onChange={e => this.setState({ u_desc: e.target.value })}
      />

       <TextField
        floatingLabelText='申请说明'
        floatingLabelFixed={true}
        fullWidth={true}
        multiLine={true}
        onChange={e => this.setState({ t_desc: e.target.value })}
      />
    </Dialog>


        <Snackbar
          open={this.state.snack_open}
          message={this.state.snack_msg}
          autoHideDuration={4000}
        />
       </div>
    );
  }
}

Tab1List.propTypes = {
  items: PropTypes.array.isRequired,
};

export default createContainer(props => {
  //初始加载,无需数据
  if(!props.cuid)
    return{
      items:[]
    };

  if(props.cuid){
    Meteor.call('trans.getprojects',props.cuid,
            function(err, result){
              if(err){
                  console.log(err);
              } else {
                  myallprojects = [];
                  result.forEach((usr) => {
                    myallprojects.push(<MenuItem value={usr.title} key={usr.userId} primaryText={usr.title} />);
                });
              }
          });     
  }
  
  

  Meteor.subscribe('transactions_history',{cuid:props.cuid,tuid:props.tuid});
  let qor = props.tuid?[{ userTo: props.cuid, userFrom: props.tuid},{userFrom: props.cuid, userTo: props.tuid}]
    : [{ userTo: props.cuid },{userFrom: props.cuid}];
  //console.log('props:'+props);
  return {
    items: Transactions.find({$or: qor}, 
    {sort: { createdAt: 1 }}).fetch(),
  };


}, Tab1List);